define([
    'base',
    'bootstrapDialog',
    'msgTool',
    'bootstrapTable'
], function (base, BootstrapDialog,msgTool) {
    //默认加载基础库
    base();

    /**
     * form表单转换成json
     */
    function getFormJson(form) {
        var data = {};
        var a = $(form).serializeArray();
        $.each(a, function () {
            if (data[this.name] !== undefined) {
                if (!data[this.name].push) {
                    data[this.name] = [data[this.name]];
                }
                data[this.name].push(this.value || '');
            } else {
                data[this.name] = this.value || '';
            }
        });
        return data;
    }

    return {
        list: function () {
            var myTable = $('#dataList');
            var tableRefresh = function () {
                myTable.bootstrapTable('refresh', {url: 'api.json'})
            };
            //table按需刷新动作
            var doAction = function (obj) {
                myTable.bootstrapTable('refresh', {url: 'api.json?pid=' + obj.id})
            };

            //table当前行的响应事件
            window.operateEvents = {
                'click .update': function (e, value, row) {
                    winModal("编辑", row);
                },

                'click .status': function (e, value, row) {
                    $.baseUtils.oneStatus({
                        row: row,
                        tableName: myTable,
                        nameText: '申请人',
                        nameValue: row.name,
                        url: '../status/action'
                    });
                },
                'click .delete': function (e, value, row) {
                    $.baseUtils.oneDelete({
                        row: row,
                        tableName: myTable,
                        nameText: '申请人',
                        nameValue: row.name,
                        url: '../delete/action'
                    });
                }
            };

            //table表格
            myTable.bootstrapTable({
                url: 'api.json', // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                fixedColumns: true,//自动修复
                queryParams: queryParams,//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
                columns: [{ // 列设置
                    field: 'state',
                    checkbox: true // 使用复选框
                },
                    {
                        field: 'id',
                        title: '编号'
                    }, {
                        field: 'name',
                        title: '姓名'
                    }, {
                        field: 'sex',
                        title: '性别'
                    }, {
                        field: 'nation',
                        title: '民族'
                    }, {
                        field: 'idCardNo',
                        title: '身份证'
                    },
                    {
                        field: 'address',
                        title: '家庭住址'
                    }, {
                        field: 'createTime',
                        title: '申请时间',
                        align: 'center'
                    }, {
                        field: 'status',
                        title: '状态',
                        align: 'center',
                        formatter: function (value, row, index) {
                            if (value === 1) {
                                return '<span class="label label-primary">正常</span>';
                            } else {
                                return '<span class="label label-danger">已禁</span>';
                            }
                        }
                    }, {
                        field: 'action',
                        title: '操作',
                        align: 'center',
                        formatter: operateFormatter,
                        events: operateEvents
                    }
                ]
            });

            //搜索刷新
            $('#search').on('click', function () {
                tableRefresh();
            });

            //toolbar按钮相应事件
            //新增
            $(".toolbar-save").on('click', function () {
                winModal("新增", null);
            });
            //刷新
            $(".toolbar-refresh").on('click', function () {
                tableRefresh();
            });

            //批量修改状态
            $(".toolbar-batchStatus").on('click', function () {
                var entityList = myTable.bootstrapTable('getSelections');
                var row = [], names = [];
                $.each(entityList, function (i, v) {
                    names.push(v.name);
                    row.push(v.id);
                });
                if (row.length > 0) {
                    $.baseUtils.batchAction({
                        row: row,
                        tableName: myTable,
                        nameText: '申请人',
                        nameValue: names,
                        url: '../status/batchAction'
                    });
                } else {
                    msgTool.error("请选择虽少一条记录后再操作", "信息提示");
                }

            });


            //搜索参数传递
            function queryParams(params) {
                params.search = $(".searchValue").val().trim();
                return {
                    limit: params.limit,
                    offset: params.offset,
                    search: params.search
                };
            }

            //回显
            function responseHandler(res) {
                return res.rows;
            }

            //模态框
            function winModal(title, row) {
                BootstrapDialog.show({
                    type: BootstrapDialog.TYPE_DEFAULT,
                    tabindex: null,//解决select2搜索框失去焦点的问题
                    title: title,
                    closable: true,	//关闭箭头启动
                    closeByBackdrop: false,	//点击空白不消失
                    closeByKeyboard: true,//ESC取消禁用
                    message: $('<div></div>').load('../save/form.html'),
                    data: {
                        'row': row
                    },
                    buttons: [{
                        label: '取消',
                        cssClass: 'btn-white cancel',
                        icon: 'fa fa-times',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }, {
                        label: '提交' + title,
                        //hotkey: 13,//回车提交
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialog) {
                            //返回验证结果
                            var flag = false;
                            flag = $("#winModal").validate().form();
                            if (flag) {
                                $.baseUtils.ajax({
                                    dialog: dialog,
                                    url: '../save/action',
                                    data: $("#winModal").serialize(),
                                    text: "保存",
                                    isTable: true,
                                    tableName: '#dataList',
                                    isDialog: true
                                })
                            }
                        }
                    }],
                    onshown: function (dialog) {
                        if (row != null) {
                            $('#id').val(row.id);
                        }
                    }
                });
            }
        },
        recordList: function () {
            var myTable = $('#dataList');
            var tableRefresh = function () {
                myTable.bootstrapTable('refresh', {url: 'api.json'})
            };
            //table按需刷新动作
            var doAction = function (obj) {
                myTable.bootstrapTable('refresh', {url: 'api.json?pid=' + obj.id})
            };

            //table当前行的响应事件
            window.operateEvents = {
                'click .info': function (e, value, row) {
                    winModal("详情", row);
                },


                'click .status': function (e, value, row) {
                    BootstrapDialog.show({
                        title: "重置领取状态",
                        message: '确认要重置' + row.name + "的《" + row.itemInfo + '》的领取状态吗?',
                        type: BootstrapDialog.TYPE_DEFAULT,
                        closable: true,
                        draggable: true,
                        buttons: [{
                            label: '取消',
                            cssClass: 'btn-white',
                            icon: 'fa fa-times',
                            action: function (dialogItself) {
                                dialogItself.close();
                            }
                        }, {
                            label: '重置未领取',
                            cssClass: 'btn-warning',
                            icon: 'fa fa-clock-o',
                            action: function (dialogItself) {
                                $.ajax({
                                    url: "/personalRecord/resetReceive/action",
                                    method: "POST",
                                    data: {
                                        id: row.id,
                                        resetStatus: 1
                                    },
                                    success: function (data) {
                                        console.log(data);
                                        if (data.success) {
                                            msgTool.success("恭喜您，领取状态已重置为未领取！", "信息提示");
                                            tableRefresh();
                                            dialogItself.close();
                                            return false;
                                        } else {
                                            msgTool.error("警告，" + data.msg, "错误提示");
                                            tableRefresh();
                                            dialogItself.close();
                                            return false;
                                        }
                                    },
                                    error: function (jqXHR) {
                                        msgTool.error(jqXHR.status + " (" + jqXHR.statusText + ")", "错误提示");
                                        tableRefresh();
                                        dialogItself.close();
                                        doAction();
                                        return false;
                                    }
                                })
                            }
                        },
                            {
                                label: '重置已领取',
                                cssClass: 'btn-primary',
                                icon: 'fa fa-check',
                                action: function (dialogItself) {
                                    $.ajax({
                                        url: "/personalRecord/resetReceive/action",
                                        method: "POST",
                                        data: {
                                            id: row.id,
                                            resetStatus: 0
                                        },
                                        success: function (data) {
                                            console.log(data);
                                            if (data.success) {
                                                msgTool.success("恭喜您，领取状态已重置为已领取！", "信息提示");
                                                tableRefresh();
                                                dialogItself.close();
                                                return false;
                                            } else {
                                                msgTool.error("警告，" + data.msg, "错误提示");
                                                tableRefresh();
                                                dialogItself.close();
                                                return false;
                                            }
                                        },
                                        error: function (jqXHR) {
                                            msgTool.error(jqXHR.status + " (" + jqXHR.statusText + ")", "错误提示");
                                            tableRefresh();
                                            dialogItself.close();
                                            doAction();
                                            return false;
                                        }
                                    })
                                }
                            }]
                    });
                },
                'click .delete': function (e, value, row) {
                    $.baseUtils.oneDelete({
                        row: row,
                        tableName: myTable,
                        nameText: '事项',
                        nameValue: row.name,
                        url: '../delete/action'
                    });
                }
            };

            //table表格
            myTable.bootstrapTable({
                url: 'api.json', // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                fixedColumns: true,//自动修复
                queryParams: queryParams,//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
                columns: [{ // 列设置
                    field: 'state',
                    checkbox: true // 使用复选框
                },
                    {
                        field: 'id',
                        title: '编号'
                    }, {
                        field: 'itemInfo',
                        title: '名称'
                    },
                    {
                        field: 'name',
                        title: '申请人',
                        formatter: function (value, row, index) {
                            return '<i class="fa fa-user" aria-hidden="true"></i>&emsp;' + value + '<br><i class="fa fa-id-card-o" aria-hidden="true"></i>&emsp;' + row.idCardNo;
                        }
                    },


                    {
                        field: 'leader',
                        title: '颁发机关'
                    }, {
                        field: 'itemTime',
                        title: '颁发时间',
                        align: 'center'
                    }, {
                        field: 'status',
                        title: '状态',
                        align: 'center',
                        formatter: function (value, row, index) {
                            if (value === 1) {
                                return '<span class="label label-primary">正常</span>';
                            } else {
                                return '<span class="label label-danger">已禁</span>';
                            }
                        }
                    }, {
                        field: 'action',
                        title: '操作',
                        align: 'center',
                        formatter: operateFormatter,
                        events: operateEvents
                    }
                ]
            });

            //搜索刷新
            $('#search').on('click', function () {
                tableRefresh();
            });

            //toolbar按钮相应事件
            //新增
            $(".toolbar-save").on('click', function () {
                winModal("新增", null);
            });
            //刷新
            $(".toolbar-refresh").on('click', function () {
                tableRefresh();
            });

            //批量修改状态
            $(".toolbar-batchStatus").on('click', function () {
                var entityList = myTable.bootstrapTable('getSelections');
                var row = [], names = [];
                $.each(entityList, function (i, v) {
                    names.push(v.name);
                    row.push(v.id);
                });
                if (row.length > 0) {
                    $.baseUtils.batchAction({
                        row: row,
                        tableName: myTable,
                        nameText: '事项',
                        nameValue: names,
                        url: '../status/batchAction'
                    });
                } else {
                    msgTool.error("请选择虽少一条记录后再操作", "信息提示");
                }

            });


            //搜索参数传递
            function queryParams(params) {
                params.search = $(".searchValue").val().trim();
                return {
                    limit: params.limit,
                    offset: params.offset,
                    search: params.search
                };
            }

            //回显
            function responseHandler(res) {
                return res.rows;
            }


            //模态框
            function winModal(title, row) {
                BootstrapDialog.show({
                    type: BootstrapDialog.TYPE_DEFAULT,
                    tabindex: null,//解决select2搜索框失去焦点的问题
                    title: title,
                    closable: true,	//关闭箭头启动
                    closeByBackdrop: false,	//点击空白不消失
                    closeByKeyboard: true,//ESC取消禁用
                    message: $('<div></div>').load('../save/form.html'),
                    data: {
                        'row': row
                    },
                    buttons: [{
                        label: '取消',
                        cssClass: 'btn-white cancel',
                        icon: 'fa fa-times',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }, {
                        label: '提交' + title,
                        //hotkey: 13,//回车提交
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialog) {
                            //返回验证结果
                            var flag = false;
                            flag = $("#winModal").validate().form();
                            if (flag) {
                                $.baseUtils.ajax({
                                    dialog: dialog,
                                    url: '../save/action',
                                    data: $("#winModal").serialize(),
                                    text: "保存",
                                    isTable: true,
                                    tableName: '#dataList',
                                    isDialog: true
                                })
                            }
                        }
                    }],
                    onshown: function (dialog) {
                        if (row != null) {
                            $('#id').val(row.id);
                        }
                    }
                });
            }
        },
    }
});






